import java.util.Enumeration;
import java.util.Vector;
import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;

public class GameDiscoverer implements DiscoveryListener {

	private Vector m_Devices = new Vector();
	private Vector m_Services = new Vector();
	private DiscoveryAgent m_Agent;
	private String m_ConnectionURL = null;
	private GameDiscoveryListener m_Listener;
	
	public GameDiscoverer() throws BluetoothStateException {
		m_Agent = LocalDevice.getLocalDevice().getDiscoveryAgent();
	}
	
	public void deviceDiscovered(RemoteDevice arg0, DeviceClass arg1) {
		if (!m_Devices.contains(arg0)) {
			m_Devices.addElement(arg0);
		}
	}

	public void inquiryCompleted(int arg0) {
        Enumeration e = m_Devices.elements();
        
        while (e.hasMoreElements()) {
        	RemoteDevice device = (RemoteDevice)e.nextElement();
        	UUID[] ids = new UUID[1];
        	ids[0] = new UUID("F0E0D0C0B0A000908070605040302011", false);
        	try {
        		m_Agent.searchServices(null, ids, device, this);
			} catch (BluetoothStateException e1) {
				e1.printStackTrace();
			}
        }
	}

	public void serviceSearchCompleted(int arg0, int arg1) {
		if (m_Services.size() > 0) {
			ServiceRecord s = ((ServiceRecord) m_Services.elementAt(0));
			m_ConnectionURL = s.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
		}
		m_Listener.discoveryComplete(this);
	}

	public void servicesDiscovered(int arg0, ServiceRecord[] arg1) {
		m_Services.addElement(arg1[0]);
	}

	public String getConnectionURL() {
		return m_ConnectionURL;
	}
	
	public boolean serverFount() {
		return (m_ConnectionURL != null); 
	}
	
	public void start(GameDiscoveryListener listener) throws BluetoothStateException {
		m_Listener = listener;
		m_Agent.startInquiry(DiscoveryAgent.GIAC, this);
	}
}
